package com.ppp.searchHelp.DB;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Timer;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.ppp.searchHelp.util.AppConfig;
import com.ppp.searchHelp.util.StringUtil;

public class TimerListenWeb implements ServletContextListener {

	private Timer timer = null; 
	
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		timer.cancel();
	}
	
	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		if(Boolean.TRUE.toString().toLowerCase().equals(AppConfig.getStr("openTask", "fasle").toLowerCase())){
			String startDate = AppConfig.getStr("startDate");
			Long delay = AppConfig.getLong("delay")*1000;
			Long period = AppConfig.getLong("period",600L)*1000;
			timer = new Timer(true);
			
			if(delay != 0L){
				timer.schedule(new DBTask(), delay, period);
			}else if(!StringUtil.isBlank(startDate)){
				SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				try {
					timer.schedule(new DBTask(), sf.parse(startDate), period);
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
